package com.treasure.common.threadpool;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sunhongmin
 * @date 2023/09/03 8:34 下午
 * @description 公用线程池枚举类 不同业务请使用专有的线程池并定义有业务意义的线程池名称
 */
public enum GlobalThreadPoolEnum {
    /**
     * 后台任务线程池
     */
    GLOBAL_BACKTASK_THREAD_POOL("后台任务", new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(8), new CustomThreadFactory("后台任务服务线程池"))),
    ;


    GlobalThreadPoolEnum(String poolName) {
        this(poolName, Executors.newFixedThreadPool(4, new CustomThreadFactory(poolName)));
    }

    GlobalThreadPoolEnum(String poolName, ExecutorService executorService) {
        this.poolName = StringUtils.isBlank(poolName) ? "undef" : poolName;
        this.executorService = executorService;
    }

    // 线程池名称-同一线程池派生的线程具有相同前缀
    private String poolName;

    // 应使用线程工厂来创建有意义的线程
    private final ExecutorService executorService;

    /**
     * 自定义线程工厂类
     */
    private static class CustomThreadFactory implements ThreadFactory {

        private final AtomicInteger count = new AtomicInteger(0);
        private final String poolName;

        public CustomThreadFactory(String poolName) {
            this.poolName = poolName;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String threadName = poolName + "_Thread_" + count.addAndGet(1);
            t.setName(threadName);
            return t;
        }
    }

    /**
     * 获取线程池实例
     *
     * @return
     */
    public ExecutorService getExecutorService() {
        return executorService;
    }
}


